package com.tsxy.mall.controller.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.tsxy.mall.entity.Order;
import com.tsxy.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PayController {
    /*@Autowired
    DonaItemService donaItemService;
    @Autowired
    DonaService donaService;*/
    //appid
    private final String APP_ID = "2021000119638146";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDmCl7X+IfXpzzV+zYKbSWKL0Y2hTJWPjH9n4gDmwT2goH5+u3xc0V0HSnQ/lwhty7r3u4QJWoxejzBIOhxoqusqvLk5Z6nMcgsL3MMfGaQ/ONxgwQTnjSnswPDmBeVI7FJ3Ba8/cMW9GTuv837cWR38/hhQRi0oqvZb3VyiSn6yzmGJyb61qMbRzXZK2+Hk3KR4ykduC++27EuMkdEB9id8YgEvrF81l44qv6TMwlRHEaqVbHbJcfMYJPFdLDaCqAQkXUlmG/Eo1tH7JOVzTG7iTkkoYQ6mXmRcuqFsU406f8hXedHJW6Ksh7ZM5UKWb7tV6N0othr6eK4cXfjyyJ3AgMBAAECggEBANtsKOt4dJqPOsggxntLgPM+BIscodcBnE1/Tg2iYCmCctgvMaeNfEI1Tx26gcbnJCp4ijt8dL6dCjZtXUqHD5mztdv/6kUwhu8ek27lei/yCEDN56WO0krjxkNbX6MyWHlLJaU/qEbM9zmEWsXscxi37cNWhGpIgAL2/eAyVYiRYWDbg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 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh6nU39lSdwHGnR+OEfhGc+AQzx0e2M9529VIIF4waVkEG4Hgoh9KS94AMAGb//B+gZjBAI8jXRMgnDI42rOfDXMICIlwmmw5sPeX2DYF7SmOoAAM3CDfXh4Q7yVDv51vZhmfeP0QDyiGTUj2pGFclcduIuRjUf7EX4XO0Y+Q0Bg0m0bfE7hFmaXG5dXJT9mfXGhkR72eaDq9PaS4hyQm4+AGxLRPHBMy50qVcUmXKPuHG6bPq3DgfBxk03sFiBDSvTRTgU0rIck6jp8wSl/TzjFDS+In4gw1EN0CKvOH3GOqsBW+km53o/aYK6mRPWYSdhDGcAs62YtTIXwR7CHuNQIDAQAB+7z4/nRXYCxc9XBynqtnJzronKm9Wv+7sswJI6g3Qn2SdjFxWHoQDrEqXKQALv2YVqE7R+BZqTS5TkDerQI1l+Nq3m7oemztrlx+96iAR5KxYO+tTr1u3XQZmjtjlqbty50DmxRCgEqJKYEu6CD+r1vi+2SXOUKnCJzsE8vHojS+Vk5oGbZYnX6Esw2TVeiCkmQ814CBwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8001/returnUrl";

    @Autowired
    private OrderService orderService;

    @RequestMapping("/pay")
    public  String test(){
        return "pay";
    }

    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @ResponseBody
    @RequestMapping("/pay/alipay")
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") String dona_money,
                         @RequestParam("dona_id") String dona_id,
                         @RequestParam("orderId") String orderId,
                         @RequestParam("addressId") String addressId) throws AlipayApiException {
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id",Integer.valueOf(dona_id));
        session.setAttribute("addressId",addressId);
        Order order = new Order();
        order.setAddressId(Integer.valueOf(addressId));
        orderService.updateStatus(order);
        //生成订单号（支付宝的要求？）
        /*String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

        String OrderNum = time+user;*/

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(orderId,Float.valueOf(dona_money),"ghjk");
    }

    /*
   参数1：订单号
   参数2：订单金额
   参数3：订单名称
    */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,Float totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

    @RequestMapping("/returnUrl")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session, Model model) throws AlipayApiException, UnsupportedEncodingException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+money);

            //在这里编写自己的业务代码（对数据库的操作）
            Integer addressId = Integer.valueOf((String)session.getAttribute("addressId"));
            Order order = new Order();
            order.setId(out_trade_no);
            order.setZFBId(trade_no);
            order.setAddressId(addressId);
            order.setStatus(1);
            orderService.updateStatus(order);
			/*
			################################
			*/
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag",1);
            model.addAttribute("msg","支持");
            return "user/orderList";
        }else{
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag",0);
            model.addAttribute("msg","支持");
            return "common/payTips";
        }
    }


}
